﻿using supermarket.method;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace supermarket
{
    public partial class supintegralexchange : Form
    {
        public SqlConnection sql = new Classgetsql().getcon();
        public supintegralexchange ( string role )
        {
            InitializeComponent();
            if (role.ToLower() == "admin")
            {
                btnRedeem.Visible = false;
            }
            else
            {
                btnRedeem.Visible = true;

            }
        }
        private void supintegralexchange_Load ( object sender, EventArgs e )
        {
            // 加载兑换记录
            try
            {
                // 加载会员下拉框数据
                string userQuery = "SELECT id,name+'_'+number as  name FROM Table_user ORDER BY name";
                using (SqlCommand cmd = new SqlCommand(userQuery, sql))
                {
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    adapter.Fill(dt);
                    // 创建一个新的行，并插入到第一行
                    DataRow newRow = dt.NewRow();
                    newRow["ID"] = 0;
                    newRow["Name"] = "请选择";
                    dt.Rows.InsertAt(newRow, 0);
                    cboUser.DataSource = dt;
                    cboUser.DisplayMember = "name";
                    cboUser.ValueMember = "id";
                }

                // 加载礼品下拉框数据
                string giftQuery = "SELECT id, giftname FROM Table_gift WHERE number > 0 ORDER BY giftname";
                using (SqlCommand cmd = new SqlCommand(giftQuery, sql))
                {
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    adapter.Fill(dt);
                    // 创建一个新的行，并插入到第一行
                    DataRow newRow = dt.NewRow();
                    newRow["ID"] = 0;
                    newRow["giftname"] = "请选择";
                    dt.Rows.InsertAt(newRow, 0);
                    cboGift.DataSource = dt;
                    cboGift.DisplayMember = "giftname";
                    cboGift.ValueMember = "id";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            loadGiftTable();
        }

        public void loadGiftTable ()
        {
            string query = @"SELECT id, giftname, username, integral, upload_time,phone 
                                    FROM Redeem  where 1=1";

            if (cboUser.SelectedValue + "" != "0")
            {
                int userId = Convert.ToInt32(cboUser.SelectedValue);
                query += string.Format(" and userid='{0}'", userId);
            }
            if (cboGift.SelectedValue + "" != "0")
            {
                int giftId = Convert.ToInt32(cboGift.SelectedValue);
                query += string.Format(" and giftid='{0}'", giftId);
            }
            if (!string.IsNullOrEmpty(txtGiftPhone.Text))
            {
                query += string.Format(" and phone like '%{0}%'", txtGiftPhone.Text);
            }

            query += " ORDER BY upload_time DESC";

            using (SqlCommand cmd = new SqlCommand(query, sql))
            {
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                adapter.Fill(dt);
                dgvGiftsNew.DataSource = dt;

                // 设置时间格式
                if (dgvGiftsNew.Columns.Contains("upload_time"))
                {
                    dgvGiftsNew.Columns["upload_time"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
                }

            }
        }

        #region 积分兑换功能
        private void btnSearch_Click ( object sender, EventArgs e )
        {
            loadGiftTable();
        }
        private void btnRedeem_Click ( object sender, EventArgs e )
        {
            if (cboUser.SelectedValue + "" == "0" || cboGift.SelectedValue + "" == "0")
            {
                MessageBox.Show("请选择会员和礼品！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                if (sql.State != ConnectionState.Open)
                {
                    sql.Open();
                }

                // 获取选中的会员和礼品信息
                int userId = Convert.ToInt32(cboUser.SelectedValue);
                int giftId = Convert.ToInt32(cboGift.SelectedValue);

                // 查询会员积分和礼品所需积分
                string checkQuery = @"SELECT u.integral, g.integral as required_points, g.number as stock, u.name as username,u.number as phone, g.giftname 
                                    FROM Table_user u, Table_gift g 
                                    WHERE u.id = @UserId AND g.id = @GiftId";

                int memberPoints = 0;
                int requiredPoints = 0;
                int stock = 0;
                string username = "";
                string giftname = "";
                string phone = "";

                using (SqlCommand cmd = new SqlCommand(checkQuery, sql))
                {
                    cmd.Parameters.AddWithValue("@UserId", userId);
                    cmd.Parameters.AddWithValue("@GiftId", giftId);

                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            memberPoints = Convert.ToInt32(reader["integral"]);
                            requiredPoints = Convert.ToInt32(reader["required_points"]);
                            stock = Convert.ToInt32(reader["stock"]);
                            username = reader["username"].ToString();
                            giftname = reader["giftname"].ToString();
                            phone = reader["phone"].ToString();
                        }
                    }
                }

                // 检查积分是否足够
                if (memberPoints < requiredPoints)
                {
                    MessageBox.Show("会员积分不足，无法兑换该礼品！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 检查库存是否足够
                if (stock <= 0)
                {
                    MessageBox.Show("该礼品库存不足！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }

                // 确认兑换
                DialogResult result = MessageBox.Show(
                    $"确定要使用 {requiredPoints} 积分兑换 {giftname} 吗？",
                    "确认兑换",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question);

                if (result == DialogResult.Yes)
                {
                    // 开始事务
                    using (SqlTransaction transaction = sql.BeginTransaction())
                    {
                        try
                        {
                            // 更新会员积分
                            string updatePointsQuery = @"UPDATE Table_user 
                                                       SET integral = integral - @Points 
                                                       WHERE id = @UserId";
                            using (SqlCommand updateCmd = new SqlCommand(updatePointsQuery, sql, transaction))
                            {
                                updateCmd.Parameters.AddWithValue("@Points", requiredPoints);
                                updateCmd.Parameters.AddWithValue("@UserId", userId);
                                updateCmd.ExecuteNonQuery();
                            }

                            // 更新礼品库存
                            string updateStockQuery = @"UPDATE Table_gift 
                                                      SET number = number - 1 
                                                      WHERE id = @GiftId";
                            using (SqlCommand updateCmd = new SqlCommand(updateStockQuery, sql, transaction))
                            {
                                updateCmd.Parameters.AddWithValue("@GiftId", giftId);
                                updateCmd.ExecuteNonQuery();
                            }

                            // 添加兑换记录
                            string insertRedeemQuery = @"INSERT INTO Redeem (giftid, giftname, userid, username, integral, upload_time,phone) 
                                                       VALUES (@GiftId, @GiftName, @UserId, @Username, @Points, @UploadTime, @Phone)";
                            using (SqlCommand insertCmd = new SqlCommand(insertRedeemQuery, sql, transaction))
                            {
                                insertCmd.Parameters.AddWithValue("@GiftId", giftId);
                                insertCmd.Parameters.AddWithValue("@GiftName", giftname);
                                insertCmd.Parameters.AddWithValue("@UserId", userId);
                                insertCmd.Parameters.AddWithValue("@Username", username);
                                insertCmd.Parameters.AddWithValue("@Phone", phone);
                                insertCmd.Parameters.AddWithValue("@Points", requiredPoints);
                                insertCmd.Parameters.AddWithValue("@UploadTime", DateTime.Now);
                                insertCmd.ExecuteNonQuery();
                            }

                            // 提交事务
                            transaction.Commit();
                            MessageBox.Show($"兑换成功！原积分：{memberPoints},兑换后积分:{memberPoints - requiredPoints}", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                            // 刷新兑换记录
                            RefreshRedeemRecords();
                            cboUser.SelectedIndex = 0;
                            cboGift.SelectedIndex = 0;
                        }
                        catch (Exception ex)
                        {
                            // 回滚事务
                            transaction.Rollback();
                            throw new Exception($"兑换失败：{ex.Message}");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"兑换过程中发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 确保连接被关闭
                if (sql.State == ConnectionState.Open)
                {
                    sql.Close();
                }
            }
        }

        private void RefreshRedeemRecords ()
        {
            try
            {
                if (sql.State != ConnectionState.Open)
                {
                    sql.Open();
                }

                string query = @"SELECT id, giftname, username, integral, upload_time,phone 
                                FROM Redeem 
                                ORDER BY upload_time DESC";

                using (SqlCommand cmd = new SqlCommand(query, sql))
                {
                    SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                    DataTable dt = new DataTable();
                    adapter.Fill(dt);
                    dgvGiftsNew.DataSource = dt;

                    // 设置时间格式
                    if (dgvGiftsNew.Columns.Contains("upload_time"))
                    {
                        dgvGiftsNew.Columns["upload_time"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
                    }

                    // 自动调整列宽
                    dgvGiftsNew.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.DisplayedCells);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"刷新兑换记录时发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 确保连接被关闭
                if (sql.State == ConnectionState.Open)
                {
                    sql.Close();
                }
            }
        }
        #endregion

    }
}
